﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;

using FirstFloor.Documents.Services.Storage;

namespace FirstFloor.Documents.Services.RequestHandlers
{
    /// <summary>
    /// Returns the list of documents found in the document store in XML format.
    /// </summary>
    public class ListDocumentsHandler
        : IRequestHandler
    {
        /// <summary>
        /// Handles the request.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="store">The store.</param>
        public void HandleRequest(HttpContext context, IDocumentStore store)
        {
            var documents = store.GetDocuments();

            context.Response.ContentType = "text/xml";
            using (var writer = XmlWriter.Create(context.Response.OutputStream)) {
                writer.WriteStartElement("Documents");
                foreach (var document in documents) {
                    writer.WriteStartElement("Document");
                    writer.WriteAttributeString("Name", document.Title);
                    writer.WriteAttributeString("Author", document.Author);
                    writer.WriteAttributeString("PageCount", document.PageCount.ToString(CultureInfo.InvariantCulture));
                    if (document.ThumbnailUri != null) {
                        writer.WriteAttributeString("Thumbnail", document.ThumbnailUri.ToString());
                    }

                    // construct full uri to document
                    var uri = new UriBuilder(context.Request.Url);
                    uri.Query = document.Name;
                    //writer.WriteAttributeString("PackageUri", );
                    writer.WriteAttributeString("WebPackageUri", uri.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
        }
    }
}
